package org.ofbiz.wvtools.ecpayutil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.ecpayutil.domain.AioCheckOutALL;

public class EcpayServices {
    public static String module = EcpayServices.class.getName();
    public static AllInOne all;

    private static void initial() {
	all = new AllInOne("");
    }

    public static Map<String, Object> getCoOrderEcpayWebPrepay(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Debug.log("createEcOrder   === start");
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	String orderId = (String) context.get("orderId");
	    try {
		GenericValue pay = delegator.findOne("PaymentGateway", UtilMisc.toMap("baseId", "ECPAY_PAY"), false);
		String returnUrl = pay.getString("phoneNotifyUrl2");

		GenericValue orderHeader = delegator.findOne("LionOrderHeaderAndProduct",
		    UtilMisc.toMap("orderId", orderId), false);
		//转台币
		double rate = 4.2;
		rate = 4.2 + 0.1;
		String total_fee = String.valueOf(orderHeader.getBigDecimal("grandTotalAmount").doubleValue()*rate);
		if (total_fee.contains(".")) {
		total_fee = total_fee.substring(0, total_fee.indexOf("."));
		}
		if(total_fee.equals("0")) {
		total_fee = "1";
		}
		String product_name = orderHeader.getString("productName");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateNowStr = sdf.format(d);
		initial();
		AioCheckOutALL obj = new AioCheckOutALL();
		UUID uid = UUID.randomUUID();
		String twOrderId = uid.toString().replaceAll("-", "").substring(0, 20);
		obj.setMerchantTradeNo(twOrderId);
//    	        obj.setMerchantTradeNo(orderId);
    	        obj.setMerchantTradeDate(dateNowStr);
    	        obj.setTotalAmount(total_fee);
    	        obj.setTradeDesc(product_name);
    	        obj.setItemName(orderId);
    	        obj.setReturnURL(returnUrl);
    	        obj.setNeedExtraPaidInfo("N");
		String form = all.aioCheckOut(obj, null);
		result.put("formUrl", form);
		
		GenericValue orderHeader2 = delegator.findOne("LionOrderHeader",
			    UtilMisc.toMap("orderId", orderId), false);
		orderHeader2.set("twRate", BigDecimal.valueOf(rate));
		orderHeader2.set("twTotalAmount", BigDecimal.valueOf(Long.valueOf(total_fee)));
		orderHeader2.set("twOrderId", twOrderId);
		orderHeader2.store();
	    } catch (GenericEntityException e) {
		e.printStackTrace();
	    }
	
	return result;
    }

    /**
     * 异步返回
     */
    @SuppressWarnings("rawtypes")
    public static String ecPayOrderNotify(HttpServletRequest request, HttpServletResponse response) {
	try {
	    Delegator delegator = (Delegator) request.getAttribute("delegator");
	    Map<String,String> params = new HashMap<String,String>();
	    Map requestParams = request.getParameterMap();
	    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
	    }
	    Debug.log("request.getParameterMap()==ecPayOrderNotify==="+params+"====="+request.getParameterMap());
	    if(UtilValidate.isEmpty(params)) {
		return "success";
	    }
	    
	    String MerchantTradeNo = params.get("MerchantTradeNo");
	    String TradeNo = params.get("TradeNo");
	    String RtnCode = params.get("RtnCode");
	    GenericValue orderHeader = EntityUtil.getFirst(delegator.findByAnd("LionOrderHeader", UtilMisc.toMap("twOrderId", MerchantTradeNo),null,false));
	    String statusId = orderHeader.getString("statusId");
	    if (RtnCode.equals("1")) {
		if (UtilValidate.isNotEmpty(orderHeader) && "ORDER_CREATED".equals(statusId)) {
		    orderHeader.set("statusId", "ORDER_APPROVED");
		    orderHeader.set("paymentStatusId", "INVOICE_RECEIVED");
		    orderHeader.set("transactionId", TradeNo);
		    orderHeader.store();
		}
	    }else {
		return "error";
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return "success";
    }

}
